# display_advice.py
import json
from waveshare_epd import epd7in5_V2
from PIL import Image, ImageDraw, ImageFont

# 配置参数
DATA_FILE = "env_data.json"
ADVICE_FILE = "ai_advice.json"
FONT_PATH = "wqy-microhei.ttc"

class DisplayManager:
    def __init__(self):
        self.epd = epd7in5_V2.EPD()
        self.epd.init()
        self.font_title = ImageFont.truetype(FONT_PATH, 24)
        self.font_data = ImageFont.truetype(FONT_PATH, 20)
        self.font_advice = ImageFont.truetype(FONT_PATH, 18)

    def load_files(self):
        """读取数据文件"""
        try:
            with open(DATA_FILE) as f:
                data = json.load(f)
            with open(ADVICE_FILE) as f:
                advice = json.load(f)['advice']
            return data, advice
        except Exception as e:
            print(f"文件读取失败：{str(e)}")
            exit(1)

    def wrap_text(self, text, font, max_width):
        """文本换行处理"""
        lines = []
        current_line = []
        for word in text.split():
            test_line = ' '.join(current_line + [word])
            if font.getsize(test_line)[0] < max_width:
                current_line.append(word)
            else:
                lines.append(' '.join(current_line))
                current_line = [word]
        lines.append(' '.join(current_line))
        return lines

    def update_display(self):
        """更新墨水屏内容"""
        data, advice = self.load_files()
        
        image = Image.new('1', (self.epd.width, self.epd.height), 255)
        draw = ImageDraw.Draw(image)
        
        # 绘制标题
        draw.text((10, 10), "智能农业监测", font=self.font_title, fill=0)
        
        # 绘制传感器数据
        y = 50
        draw.text((10, y), f"温度: {data['temp']}℃", font=self.font_data, fill=0)
        draw.text((300, y), f"湿度: {data['humidity']}%", font=self.font_data, fill=0)
        draw.text((600, y), f"气压: {data['pressure']}hPa", font=self.font_data, fill=0)
        
        # 绘制分隔线
        draw.line((10, 90, 790, 90), fill=0, width=2)
        
        # 绘制建议
        y = 100
        lines = self.wrap_text(advice, self.font_advice, 780)
        for line in lines:
            draw.text((10, y), line, font=self.font_advice, fill=0)
            y += 25
            if y > 450: break
        
        self.epd.display(self.epd.getbuffer(image))
        self.epd.sleep()

if __name__ == "__main__":
    try:
        display = DisplayManager()
        display.update_display()
        print("屏幕更新完成")
    except Exception as e:
        print(f"显示错误：{str(e)}")